// 绘制工具类，只负责绘制，不负责图层管理
export class DrawUtils {
  constructor(map,onDrawComplete) {
    this.map = map
    this.currentShape = null
    this.tempLayer = null
    this.eventHandlers = {}
    this.drawPolyline = null

    // 需要有一个回调函数，用于绘制完成后的回调
    this.onDrawComplete = onDrawComplete
  }

  // ====== 通用入口 ======
  startDraw(type, startPoint) {
    switch (type) {
      case 'point':
        this.startDrawPoint(startPoint)
        break
      case 'free_line':
        this.startDrawFreeLine(startPoint)
        break
      case 'line':
        this.startDrawLine(startPoint)
        break
      case 'polygon':
        this.startDrawPolygon(startPoint)
        break
      case 'circle':
        this.startDrawCircle(startPoint)
        break
      case 'rectangle':
        this.startDrawRectangle(startPoint)
        break
      default:
        console.warn('未知绘制类型:', type)
    }
  }

  // ====== 点 ======
  startDrawPoint(startPoint) {
    console.log('开始绘制点', startPoint)
    // 这里可以直接调用 drawPoint
    this.drawPoint(startPoint)
  }
  drawPoint(lngLat) {
    console.log('绘制点:', lngLat)
    // 具体实现由你完成
  }

  // ====== 自由线 ======
  /**
   * 
   * @param {*} options
   *  @param {boolean} options.isDraggable 是否禁止地图移动
   *  @param {String} options.eventType 绘制事件类型，是点击还是按下移动
   */
  startDrawFreeLine(options = {}) {
    console.log('开始自由绘制线')
    
    // 清理所有存在的旧事件
    this.clearAll()
    
    // 先禁止地图拖拽
    this.map.setDraggable(false)
    this.createLineInstance()
    // 绑定 mousedown 事件，使用更可靠的方式
    const mousedownHandler = (event) => {
      console.log('mousedown triggered', event)
      // 阻止事件冒泡，确保不被地图拦截
     
      this.handleMapeventType(event, options)
    }
    
    this.eventHandlers['mousedown'] = mousedownHandler
    this.map.on('mousedown', mousedownHandler)
  }

  handleMapeventType(event, options) {
    if (options.eventType === 'mousedown') {
      // 再次确保地图不可拖拽
      this.map.setDraggable(false)
      
      // 记录起点，初始化点数组
      this.startPoint = event.latLng || event.lngLat
      this.tempPoints = [this.startPoint]
      console.log('确认一个起点，然后开始绘制', this.startPoint)
      this.drawPolyline.updateGeometries([{
        id: 'freehand-line',
        styleId: 'line',
        paths: this.tempPoints
    }])
      // 绑定 mousemove 事件
      const mousemoveHandler = (event) => {
        console.log('mousemove triggered', event)
        // 阻止事件冒泡
        
        this.continueDrawFreeLine(event)
      }
      this.eventHandlers['mousemove'] = mousemoveHandler
      this.map.on('mousemove', mousemoveHandler)
      
      // 绑定 mouseup 事件
      const mouseupHandler = (event) => {
        console.log('mouseup triggered', event)
        // 阻止事件冒泡
        this.finishDrawFreeLine(event)
      }
      this.eventHandlers['mouseup'] = mouseupHandler
      this.map.on('mouseup', mouseupHandler)
    }
  }

  continueDrawFreeLine(event) {
    console.log('continueDrawFreeLine called', event)
    
    // 持续添加点
    if (!this.tempPoints) return
    
    const point = event.latLng || event.lngLat
    if (point) {
      this.tempPoints.push(point)
      console.log('自由线绘制中:', point, '当前点数:', this.tempPoints.length)
      // 这里可以做预览
      this.drawPolyline.updateGeometries([{
        id: 'freehand-line',
        styleId: 'line',
        paths: this.tempPoints
    }])
    }
  }

  finishDrawFreeLine(event) {
    console.log('finishDrawFreeLine called', event)
    
    // 结束绘制，移除事件
    console.log('完成自由线绘制，总点数:', this.tempPoints ? this.tempPoints.length : 0)
     // 检查是否形成闭合区域（自动/手动）
    if (this.checkAutoClose()) {
      console.log('形成闭合区域');
      
      this.tempPoints.push(this.tempPoints[0]); // 闭合多边形（首尾相接）
        this.drawPolyline.updateGeometries([{
          id: 'freehand-line',
          styleId: 'line',
          paths: this.tempPoints
      }])
    }
    // 恢复地图拖拽
    this.map.setDraggable(true)
    
    // 这里可以将 this.tempPoints 作为一条线保存
    if (this.tempPoints && this.tempPoints.length > 1) {
      console.log('保存绘制的线:', this.tempPoints)
      // 保存逻辑
      this.onDrawComplete({
        type: 'free_line',
        data: this.tempPoints
      })
    }
    
    // 移除事件监听
    this.clearAll()
    this.tempPoints = null
    this.startPoint = null
  }
  cancelDrawFreeLine() {
    console.log('取消自由线绘制')
    // 取消自由线
  }
  // 创建线实例
  createLineInstance() {
    this.drawPolyline = new TMap.MultiPolyline({
      map: this.map,
      styles: {
        line: new TMap.PolylineStyle({
          color: '#FF0000',
          width: 4
        })
      },
      geometries: []
    })
  }

  // ====== 直线 ======
  startDrawLine(startPoint) {
    console.log('开始绘制直线', startPoint)
    // 初始化直线状态
  }
  addLinePoint(point) {
    console.log('添加直线点:', point)
    // 添加点
  }
  finishDrawLine() {
    console.log('完成直线绘制')
    // 完成直线
  }
  cancelDrawLine() {
    console.log('取消直线绘制')
    // 取消直线
  }

  // ====== 多边形 ======
  startDrawPolygon(startPoint) {
    console.log('开始绘制多边形', startPoint)
    // 初始化多边形状态
  }
  addPolygonPoint(point) {
    console.log('添加多边形点:', point)
    // 添加点
  }
  finishDrawPolygon() {
    console.log('完成多边形绘制')
    // 完成多边形
  }
  cancelDrawPolygon() {
    console.log('取消多边形绘制')
    // 取消多边形
  }

  // ====== 圆形 ======
  startDrawCircle(center) {
    console.log('开始绘制圆形，圆心:', center)
    // 初始化圆形状态
  }
  updateDrawCircle(radiusPoint) {
    console.log('更新圆形半径点:', radiusPoint)
    // 更新半径
  }
  finishDrawCircle() {
    console.log('完成圆形绘制')
    // 完成圆形
  }
  cancelDrawCircle() {
    console.log('取消圆形绘制')
    // 取消圆形
  }

  // ====== 矩形 ======
  startDrawRectangle(startPoint) {
    console.log('开始绘制矩形，起点:', startPoint)
    // 初始化矩形状态
  }
  updateDrawRectangle(endPoint) {
    console.log('更新矩形终点:', endPoint)
    // 更新终点
  }
  finishDrawRectangle() {
    console.log('完成矩形绘制')
    // 完成矩形
  }
  cancelDrawRectangle() {
    console.log('取消矩形绘制')
    // 取消矩形
  }
  // 全部清除
  clearAll() {
    for (const eventType in this.eventHandlers) {
      this.cleanupEvents(eventType)
    }
  }

   /**
   * 清理事件监听器
   */
   cleanupEvents(eventType) {
    if (this.eventHandlers[eventType]) {
      this.map.off(eventType, this.eventHandlers[eventType])
      delete this.eventHandlers[eventType]
    }
  }

  // ====== 通用 ======
  stopDraw() {
    console.log('停止所有绘制')
    // 停止所有绘制
  }
  // 检查起点终点距离是否≤阈值（自动闭合）
  checkAutoClose(threshold = 10) {
    if (this.tempPoints.length < 3) return false;
    const first = this.tempPoints[0];
    const last = this.tempPoints[this.tempPoints.length - 1];
    const dx = first.lng - last.lng;
    const dy = first.lat - last.lat;
    const distance = Math.sqrt(dx * dx + dy * dy);
    console.log('自动闭合检测:', { first, last, distance, threshold, isClosed: distance <= threshold });
    return distance <= threshold;
  }
} 